package org.alex.samples.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.alex.samples.model.ExamScore;
import org.alex.samples.model.ExamScoreVO;
import org.alex.samples.model.ExamSubScoreVO;
import org.alex.samples.model.ExamSubjectVO;
import org.alex.samples.model.ExamUserVO;
import org.alex.samples.model.ShowExamScore;
import org.alex.samples.model.Sub;
import org.alex.samples.model.User;
import org.alex.samples.service.ISubService;
import org.alex.samples.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class SubController {
	@Autowired
	private ISubService subService;
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private LocaleResolver localeResolver;
	
	@Autowired
	private MessageSource messageSource;
	
	@RequestMapping(value = "/changeLocales")
	public String changeLocale(HttpServletRequest request,HttpServletResponse response,String localeType){
		if("en_US".equals(localeType)){
			localeResolver.setLocale(request, response, Locale.US);
		}else if("zh_CN". equals(localeType)){
			localeResolver.setLocale(request, response, Locale.CHINA);
		}
		return "redirect:/subs";
	}
	
	@RequestMapping("/subs")
	public String subs(Model model,HttpSession session){
		List<ExamSubjectVO> list = subService.findAllSubs();
		
		model.addAttribute("editSub", messageSource.getMessage("page.index.edit", null,LocaleContextHolder.getLocale()));
		model.addAttribute("subList", list);
		return "sub/subList";
	}
	
	@RequestMapping(value = "/addSub",method = RequestMethod.GET)
	public String toaddSub(Model model){
		model.addAttribute("sub", new Sub());
		return "sub/addSub";
	}
	
	@RequestMapping(value = "/addSub",method = RequestMethod.POST)
	public String addSub(RedirectAttributes redirectAttributes,@Validated Sub sub,BindingResult result){
		if(result.hasErrors()){
			return "sub/addSub";
		}
		try {
			subService.createSub(sub);
			redirectAttributes.addFlashAttribute("message", "添加成功.");
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
		return "redirect:/subs";
	}
	
	@RequestMapping(value = "/editSub/{id}",method = RequestMethod.GET)
	public String toEditSub(Model model,@PathVariable int id){
		Sub sub = subService.getSubById(id);
		model.addAttribute("sub", sub);
		return "sub/editSub";
	}
	
	@RequestMapping(value = "/editSub/{id}",method = RequestMethod.POST)
	public String editSub(RedirectAttributes redirectAttributes, Sub sub,@PathVariable int id){
		try {
			subService.editSub(sub);
			redirectAttributes.addFlashAttribute("message", "修改成功.");
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
		return "redirect:/subs";
	}
	@ResponseBody
	@RequestMapping(value = "/deleteSub")
	public Map<String,Object> deleteSub( int subjectId){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("success", false);
		Sub sub = subService.getSubById(subjectId);
		
		try {
			if(sub.getStatus()==1){
				resultMap.put("success", true);
				resultMap.put("message", "已开启考试的科目不允许删除,删除失败！");
			}else{
				subService.deleteSub(subjectId);
				resultMap.put("success", true);
				resultMap.put("message", "删除成功.");
			}
			
		} catch (Exception e) {
			resultMap.put("message", "删除失败.");
			e.printStackTrace();
		}
		return resultMap;
	}
//	@RequestMapping(value = "/deleteSub/{id}",method = RequestMethod.GET)
//	public String deleteSub(RedirectAttributes redirectAttributes, @PathVariable int id){
//		try {
//			subService.deleteSub(id);
//			redirectAttributes.addFlashAttribute("message", "删除成功.");
//		} catch (Exception e) {
//			redirectAttributes.addFlashAttribute("message", "删除失败.");
//			e.printStackTrace();
//		}
//		return "redirect:/subs";
//	}
	
	@ResponseBody
	@RequestMapping(value = "/getAllStudent")
	public Map<String,Object> getAllStudent(Integer subjectId){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		
		resultMap.put("allUser", userService.findAllUsers());//获取所有学生,包括没关联的
		resultMap.put("selectedUser", subService.getAllUserBySubject(subjectId));//获取所有已关联的学生
		return resultMap;
	}
	
	@ResponseBody
	@RequestMapping(value = "/saveSubjectStudents")
	public Map<String,Object> saveSubjectStudents(@RequestParam(name = "subjectStudents[]")String[] subjectStudents,Integer subjectId){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("success", false);
		List<String> list = new ArrayList<String>();
		for(String student: subjectStudents){
			list.add(student);
		}
		try{
			//传到Service，让Service来处理
			subService.saveSubjectStudent(list,subjectId);
			resultMap.put("success", true);
		}catch(Exception e){
			e.printStackTrace();
		}
		return resultMap;
	}
	
	@RequestMapping("/studentSub")
	public String studentSub(Model model,HttpSession session){
		User userVO = (User) session.getAttribute("User");
		List<ExamSubScoreVO> list = subService.getAllUserSubs(userVO);
		
		model.addAttribute("studentSubList", list);
		return "sub/studentList";
	}
	
	@ResponseBody
	@RequestMapping(value = "/showScore",method = RequestMethod.POST)
	public ExamScoreVO showScore(HttpSession session,Integer scoreId){
		ExamScoreVO vo = subService.getScoreById(scoreId);
		return vo;
	}
	//教师管理学生成绩
	@RequestMapping("/studentScore")
	public String studentScore(Model model,HttpSession session){
		
		model.addAttribute("subjectNameList", subService.findAllSubs());
		
		return "test/testScore";
	}
	//教师查询学生成绩
	@ResponseBody
	@RequestMapping(value="/showAllScore")
	public List<ExamScoreVO> showAllScore( Integer subId, String userId,String userName,String examTime){
		System.out.println(subId+" "+userId+" "+userName+" "+examTime);
		List<ExamScoreVO> resultList = null;
		
		
//		if(subId !=0 && userId == null && userName == null && examTime == null){
			 resultList = subService.getAllScoreBysubId(subId);
			
//		}
//		if(subId ==0 && userId == null && userName == null && examTime == null){
//			
//		}
		return resultList;
		
	}
	
	
	
}
